package com.lwt.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwt.bean.Employee;
import com.lwt.bean.JsonMsg;
import com.lwt.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author Li Weitong
 * @Date 2021/1/9 21:23
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
//    默认每页显示5条数据
    private static int pageSize = 5;

    /**
     * 1.导包 jackson包
     * 2.方法上使用@RequestBody注解，将返回的对象转化为json字符串。创建jsonMsg类，额外添加返回json字符串的内容（新增状态码，提示信息等）
     * @param pageNo
     * @param model
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public JsonMsg getEmpsByAjax(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo, Model model){
        System.out.println("向服务器发送了一次ajax请求");
        PageHelper.startPage(pageNo,pageSize);
        List<Employee> list = employeeService.queryEmps();
        PageInfo pageInfo = new PageInfo(list, 6);
        return JsonMsg.success().add("pageInfo",pageInfo); // 返回的就是json字符串
    }

    /*
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo, Model model){
        PageHelper.startPage(pageNo, pageSize); // startPage后紧跟的查询是分页查询
        List<Employee> list = employeeService.queryEmps();

        PageInfo pageInfo = new PageInfo(list,6); // 使用pageInfo包装查询后的结果，将pageInfo交给页面（模型数据Model）一劳永逸,6为导航页
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

     */


    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public JsonMsg saveEmp(@Valid Employee employee, BindingResult bindingResult){
        System.out.println("saveEmp()...");
        if (bindingResult.hasErrors()) {
            // 在模态框中显示校验失败的错误信息
            HashMap<String, Object> map = new HashMap<>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println("错误的字段名"+fieldError.getField());
                System.out.println("错误的信息"+fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return JsonMsg.fail().add("errorFields",map);
        }else {
            employeeService.saveEmp(employee);
            return JsonMsg.success();
        }
    }

    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    @ResponseBody
    public JsonMsg getEmp(@PathVariable("id") Integer id){ // 此id来源于请求地址的变量{id}
        Employee employee = employeeService.queryEmp(id);
        return JsonMsg.success().add("emp",employee);
    }

    /**
     * 员工更新
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public JsonMsg updateEmp(Employee employee){
        System.out.println("更新数据"+employee);
        employeeService.updateEmp(employee);
        System.out.println("更新数据"+employee);
        return JsonMsg.success();
    }

//    @RequestMapping(value = "/emp/{id}",method = RequestMethod.DELETE)
//    @ResponseBody
//    public JsonMsg deleteEmpById(@PathVariable("id") Integer id){
//        employeeService.deleteEmpById(id);
//        return JsonMsg.success();
//    }

    /**
     * 批量删除+单个删除 二合一
     * 创造一个list集合，将用-分割的字符串转为整型放入这个集合中
     * @param ids
     * @return
     */
    @RequestMapping(value = "/emp/{ids}",method = RequestMethod.DELETE)
    @ResponseBody
    public JsonMsg deleteEmp(@PathVariable("ids") String ids){
        if (ids.contains("-")){
            List<Integer> del_list = new ArrayList<>();
            String[] split = ids.split("-");
            for (String s : split) {
                del_list.add(Integer.parseInt(s));
            }
            employeeService.deleteBatch(del_list);
        }else {
            int id = Integer.parseInt(ids);
            employeeService.deleteEmpById(id);
        }

        return JsonMsg.success();
    }

}
